import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:socket_io_client/socket_io_client.dart' as IO;
import 'package:xmshop/app/services/screenAdapter.dart';
import 'package:xmshop/app/widget/JdText.dart';

class SocketPage extends StatefulWidget {
  const SocketPage({super.key});

  @override
  State<SocketPage> createState() => _SocketPageState();
}

class _SocketPageState extends State<SocketPage> {
  late IO.Socket socket;
  bool showPhotoAction = false;
  final _scrollController = new ScrollController();
  final TextEditingController _messageController = TextEditingController();
  final _messageList = [];
  //新版本的image_picker需要实例化ImagePicker
  final picker = ImagePicker();

  @override
  void initState() {
    print("---socket---init");
    // TODO: implement initState
    super.initState();

    // Dart client
    // socket = IO.io('http://192.168.56.1:8001/');
    // socket = IO.io('http://192.168.56.1:8001/', <String, dynamic>{
    //   'transports': ['websockt']
    // });
    socket = IO.io('http://119.91.151.46:8001?roomid=1');
    socket.onConnect((_) {
      print('---connect---连接上了socket服务器---');
    });
    socket.on(
        'toClient',
        (data) => {
              setState(() {
                _messageList.add({
                  "server": true,
                  "title": data["title"],
                  "url": data["url"]
                });
              }),

              // 改变滚动条的位置
              _scrollController
                  .jumpTo(_scrollController.position.maxScrollExtent + 80)
            });

    socket.onDisconnect((_) => print('disconnect'));
  }

  // 广播
  _doEmit(value) async {
    socket.emit('toServer', {"title": value, "url": ""});
    setState(() {
      // 更新本地数据
      _messageList.add({"server": false, "title": value, "url": ""});
    });
    // 改变滚动条的位置
    _scrollController.jumpTo(_scrollController.position.maxScrollExtent + 80);
  }

  // 拍照
  _takePhoto() async {
    // picker定义在属性里面了
    final pickedFile =
        await picker.pickImage(source: ImageSource.camera, maxWidth: 400);
    if (pickedFile != null) {
      _uploadImage(File(pickedFile.path));
    } else {
      print("error: getImage is null");
    }
  }

  // 相册
  _openGallery() async {
    // picker定义在属性里面了
    final pickedFile =
        await picker.pickImage(source: ImageSource.gallery, maxWidth: 400);
    if (pickedFile != null) {
      _uploadImage(File(pickedFile.path));
    } else {
      print("error: getImage is null");
    }
  }

  // 上传图片
  _uploadImage(File file) async {
    setState(() {
      // 更新数据
      _messageList.add({"server": false, "title": "", "url": file});
    });

    //注意：dio3.x以后的版本为了兼容web做了一些修改，上传图片的时候需要把File类型转换成String类型，具体代码如下
    var uploadFile = file.path;

    //  FormData formData = FormData.fromMap(
    //     {"file": await MultipartFile.fromFile(uploadFile, filename: "xxx.jpg")});

    var response =
        await Dio().post("http://119.91.151.46:8001/imgupload", data: null);

    var data = response.data;
    var url = "http://119.91.151.46:8001${data["path"]}";

    socket.emit("toServer", {"title": "", "url": url});
    // 改变滚动条的位置
    _scrollController.jumpTo(_scrollController.position.maxScrollExtent + 80);

    // 隐藏键盘
    FocusScope.of(context).requestFocus(FocusNode());
    setState(() {
      showPhotoAction = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Socket的使用")),
      body: Stack(
        children: [
          InkWell(
            child: Container(
              padding: const EdgeInsets.only(bottom: 100),
              child: ListView.builder(
                  itemCount: _messageList.length,
                  itemBuilder: (context, index) {
                    if (_messageList[index]["server"]) {
                      //别人发的
                      var w;
                      if (_messageList[index]["url"] != "") {
                        w = Container(
                            alignment: Alignment.topLeft,
                            width: 100,
                            height: 100,
                            child: Image.network(_messageList[index]["url"]));
                      } else {
                        w = Text("${_messageList[index]["title"]}",
                            textAlign: TextAlign.left);
                      }

                      return ListTile(
                          leading: const Icon(Icons.people), title: w);
                    } else {
                      var w;
                      if (_messageList[index]["url"] != "") {
                        w = Container(
                            alignment: Alignment.topRight,
                            width: 100,
                            height: 100,
                            child: Image.network(_messageList[index]["url"]));
                      } else {
                        w = Text("${_messageList[index]["title"]}");
                      }

                      return ListTile(
                          trailing: const Icon(Icons.person_outlined),
                          title: w);
                    }
                  }),
            ),
            onTap: () {
              setState(() {
                showPhotoAction = false;
                // 隐藏键盘
                FocusScope.of(context).requestFocus(FocusNode());
              });
            },
          ),
          Positioned(
            bottom: 0,
            //注意使用ScreenAdapter 还需要 main.dart中调用 ScreenUtilInit
            width: ScreenAdapter.width(1080),
            child: Container(
              decoration: const BoxDecoration(color: Colors.white),
              width: ScreenAdapter.width(1080),
              child: Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: JdText(
                          controller: _messageController,
                          onSubmitted: (key) {
                            _doEmit(_messageController.text);
                            _messageController.text = '';
                          },
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.all(ScreenAdapter.width(20)),
                        child: Container(
                          width: ScreenAdapter.width(68),
                          height: ScreenAdapter.width(68),
                          decoration: BoxDecoration(
                            color: Colors.black12,
                            borderRadius:
                                BorderRadius.circular(ScreenAdapter.width(68)),
                          ),
                          child: InkWell(
                            child: const Icon(Icons.add),
                            onTap: () {
                              setState(() {
                                showPhotoAction = !showPhotoAction;
                              });
                            },
                          ),
                        ),
                      )
                    ],
                  ),
                  showPhotoAction
                      ? Row(
                          children: <Widget>[
                            Padding(
                              padding: const EdgeInsets.all(10),
                              child: IconButton(
                                icon: const Icon(Icons.photo_camera),
                                onPressed: () {
                                  _takePhoto();
                                },
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.all(10),
                              child: IconButton(
                                icon: const Icon(Icons.photo_library),
                                onPressed: () {
                                  _openGallery();
                                },
                              ),
                            )
                          ],
                        )
                      : Container(height: 0)
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}
